var cf = require("../../../config.js");
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
var webim = global.webim;
var webimhandler = global.webimhandler;
//获取应用实例
var app = getApp();

Page(Object.assign({}, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    app: app,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    feedsType:"time",
    list: [],
    isLoading: false,
    pageSize: 10,
    curPage: 1,
    isBottom: false,
    behaviorCount:{},
    behaviorTypeMap:{
      1:"觉得靠谱",
      // 4:"查看产品",
      7:"查看官网",
      9:"复制微信",
      3: "转发" + app.globalData.cardTitle,
      2: "查看"+ app.globalData.cardTitle,
      // 13:"查看动态",
      // 26:"咨询产品",
      12:"保存电话",
      24:"播放语音",
      11:"拨打电话",
      // 10:"复制邮箱",
      53:"点击导航",
      54:"浏览房源",
      55:"推介客户",
      56:"预约看房",
      57:"领取优惠券",
      58:"报名活动",
      59:"申领礼品"
    },
    hideDateModal:true,
    btEndDate: "",
    defBtEndDate: "",
    btStartDate: "",
    defBtStartDate: "",
    mSDate: "",
    mEDate: "",
    statList: [],
    statDetailMap:{},
    statIsLoading: false,
    statCurPage: 1,
    statIsBottom: false,
    showIndex:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.setData({
      btEndDate: util.formatDate(new Date()),
      btStartDate: util.formatDate(new Date(Date.now() - (7 * 86400000))),
      defBtEndDate: util.formatDate(new Date()),
      defBtStartDate: util.formatDate(new Date(Date.now() - (7 * 86400000))),
      eId: wx.getStorageSync('employee').id
    });
      let page = getCurrentPages();
      let { showIndex } = this.data;
     if (page.length == 1) {
         showIndex = true 
       }
       this.setData({showIndex});
    
    app.getUserInfo(this, options, function (userInfo, res) {

      cusmallToken = wx.getStorageSync('cusmallToken');
      that.queryBehaviorTrail();
      that.queryStatList();
      that.behaviorCount();
    });
  },

  changeFeedsTitle:function(e){
    let {feedstype,type} = e.currentTarget.dataset;
    this.setData({
      feedsType:feedstype
    })
     //收集顾问发送信息
     app.globalData.sensors.track(type, {
      account_id: wx.getStorageSync('userId'),
      role: '置业顾问'
     });
  },
  queryBehaviorTrail(cb){
    var ctx = this;
    if (ctx.data.isLoading || ctx.data.isBottom) {
      return;
    }
    ctx.setData({ isLoading: true });
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/bahavior/queryBehaviorTrail",
      data: {
        cusmallToken: cusmallToken,
        start: (ctx.data.curPage - 1) * ctx.data.pageSize,
        eid:ctx.data.eId,
        limit: ctx.data.pageSize
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
          var list = data.model.list;
          for(let item of list){
            item.behaviorTxt = util.behaviorType(item.type, item.count);
            item.behaviorTime = util.timestampToDayHkt(item.createTime);
            // if (item.sttr1 && item.sttr1.length > 10){
            //   item.sttr1 = item.sttr1.substring(0,6) + "...";
            // }
          }
          ctx.setData({
            list: ctx.data.list.concat(list),
          });
          if (data.model.total == ctx.data.list.length) {
            ctx.setData({
              isBottom: true
            });
          }
        } else if(data.ret == -107) {
          wx.reLaunch({
            url: '/pages/load/load',
          })

        }else{
          
        }
        cb && cb();
      },
      fail() {
      },
      complete() {
        ctx.setData({ isLoading: false });
      }
    });
  },
  //
  behaviorCount(){
    var ctx = this;
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/behaviorCount",
      data: {
        cusmallToken: cusmallToken,
        startDate: ctx.data.btStartDate,
        endDate: ctx.data.btEndDate
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        if (data && 0 === data.ret) {
         ctx.setData({
           behaviorCount: data.model
         })
        } else {
        }
      },
      fail() {
      },
      complete() {
      }
    });
  },
  defResetDate() {
    var ctx = this;
    ctx.setData({
      btEndDate: ctx.data.defBtEndDate,
      btStartDate: ctx.data.defBtStartDate,
    });
    ctx.behaviorCount();
    ctx.reloadStatList();
  },
  showDateModal(){
    var ctx = this;
    ctx.setData({
      hideDateModal:false,
      mSDate: ctx.data.btStartDate,
      mEDate: ctx.data.btEndDate,
    });
  },
  hideDateModal(){
    this.setData({
      hideDateModal:true
    })
  },
  bindDateChange(e) {
    var op = e.currentTarget.dataset.op;
    if ("start" == op) {
      this.setData({
        mSDate: e.detail.value
      });
    } else if ("end" == op) {
      this.setData({
        mEDate: e.detail.value
      });
    }
  },
  fetchBehTra(e){
    var ctx = this;
    ctx.setData({
      hideDateModal: false,
      btStartDate: ctx.data.mSDate,
      btEndDate: ctx.data.mEDate,
    });
    ctx.handleCommonFormSubmit(e);
    ctx.behaviorCount();
    ctx.reloadStatList();
    ctx.hideDateModal();
  },
  toBehavior(e){
    var btype = e.currentTarget.dataset.btype;
    btype = this.data.behaviorCount[btype];
    wx.navigateTo({
      url: './behavior?bType=' + btype + "&title=" + this.data.behaviorTypeMap[btype],
    })
  },
  reloadStatList() {
    var ctx = this;
    wx.showLoading({
      title: '加载中'
    });
    ctx.setData({ statIsLoading: true });
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/memberBehaviorCountList",
      data: {
        cusmallToken: cusmallToken,
        start: 0,
        limit: ctx.data.pageSize,
        startDate: ctx.data.btStartDate,
        endDate: ctx.data.btEndDate
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.hideLoading();
        var data = res.data;
        if (data && 0 === data.ret) {
          var list = data.model.list;
          var relation = data.model.relation;
          var statMap = {};
          for (let item of relation) {
            statMap[item.memberId] = item;
          }
          for (let item of list) {
            item.behaviorCount = statMap[item.id].behaviorCount;
            item.expand = false;
          }
          ctx.setData({
     		 statList: list,
     	  });
        } else {
          wx.showToast({
            title: data.msg,
            icon:"none"
          })
        }
      },
      fail() {
      },
      complete() {
        ctx.setData({ statIsLoading: false });
      }
    });
  },
  queryStatList(cb) {
    var ctx = this;
    if (ctx.data.statIsLoading || ctx.data.statIsBottom) {
      return;
    }
    wx.showLoading({
      title: '加载中'
    });
    ctx.setData({ statIsLoading: true });
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/memberBehaviorCountList",
      data: {
        cusmallToken: cusmallToken,
        start: (ctx.data.statCurPage - 1) * ctx.data.pageSize,
        limit: ctx.data.pageSize,
        startDate: ctx.data.btStartDate,
        endDate: ctx.data.btEndDate
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.hideLoading();
        var data = res.data;
        if (data && 0 === data.ret) {
          var list = data.model.list;
          var relation = data.model.relation;
          var statMap = {};
          for (let item of relation) {
            statMap[item.memberId] = item;
          }
          for (let item of list) {
            item.behaviorCount = statMap[item.id].behaviorCount;
            item.expand = false;
          }
          ctx.setData({
     		 statList: ctx.data.statList.concat(list),
     	  });
          if (data.model.total == ctx.data.statList.length) {
            ctx.setData({
               statIsBottom: true
            });
          }
        } else {
          wx.showToast({
            title: data.msg,
            icon:"none"
          })
        }
      },
      fail() {
      },
      complete() {
        ctx.setData({ statIsLoading: false });
        cb && cb();
      }
    });
  },
  queryStatDetail(e) {
    var ctx = this;
    var idx = e.currentTarget.dataset.idx;
    var openid = ctx.data.statList[idx].openid;
    var behaviorCount = ctx.data.statList[idx].behaviorCount
    ctx.setData({
      ["statList[" + idx + "].expand"]: !ctx.data.statList[idx].expand
    });
    if (ctx.data.statDetailMap[openid]){
      return;
    }
    wx.showLoading({
      title: '加载中'
    });
    wx.request({
      url: cf.config.pageDomain + "/applet/mobile/visitcard/dataprofile/memberBehaviorCount",
      data: {
        cusmallToken: cusmallToken,
        openid: openid,
        startDate: ctx.data.btStartDate,
        endDate: ctx.data.btEndDate
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.hideLoading();
        var data = res.data;
        if (data && 0 === data.ret) {
          var statDetail = data.model;
          var list = [];
          list.push({
            name:"查看名片",
            times: statDetail["browseCard"],
            color:"#6696ff"
          });
          // list.push({
          //   name:"查看产品",
          //   times:statDetail["browseGoods"],
          //   color: "#ff9900"
          // });
          // list.push({
          //   name: "查看动态",
          //   times: statDetail["browseDynamic"],
          //   color:"#3b83ff"
          // });
          list.push({
            name: "查看官网",
            times: statDetail["browseBrand"],
            color: "#6696ff"
          });
          // list.push({
          //   name: "咨询产品",
          //   times: statDetail["consultGoods"],
          //   color: "#ff9900"
          // });
          list.push({
            name: "存储电话",
            times: statDetail["savePhone"],
            color: "#3b83ff"
          });
          list.push({
            name: "为你点赞",
            times: statDetail["thumbsCard"],
            color: "#6696ff"
          });
          list.push({
            name: "点赞标签",
            times: statDetail["thumbsLabels"],
            color: "#ff9900"
          });
          list.push({
            name: "播放语音",
            times: statDetail["hearVoice"],
            color: "#3b83ff"
          });
          // list.push({
          //   name: "购买产品",
          //   times: statDetail["buyGoods"],
          //   color: "#ff9900"
          // });
          list.push({
            name: "点击导航 ",
            times: statDetail["clickNavigation"],
            color: "#ff9900"
          });
          list.push({
            name: "浏览房源",
            times: statDetail["browseHouse"],
            color: "#ff9900"
          });
          list.push({
            name: "推介客户",
            times: statDetail["promoteCustomer"],
            color: "#ff9900"
          });
          list.push({
            name: "预约看房",
            times: statDetail["appointmentSee"],
            color: "#ff9900"
          });
          list.push({
            name: "领优惠券",
            times: statDetail["getCoupons"],
            color: "#ff9900"
          });
          list.push({
            name: "报名活动",
            times: statDetail["registationActivities"],
            color: "#ff9900"
          });
          list.push({
            name: "申领礼物",
            times: statDetail["applyGifts"],
            color: "#ff9900"
          });
          for(let item of list){
            item.per = parseFloat((item.times / behaviorCount*100).toFixed(2));
          }
          var statDetailMap = ctx.data.statDetailMap;
          statDetailMap[openid] = list;
          ctx.setData({
            statDetailMap: statDetailMap
          })
        } else {
          wx.showToast({
            title: data.msg,
            icon:"none"
          })
        }
      },
      fail() {
      },
      complete() {
      }
    });
  },
  toCustDetail(e){
    var ctx = this;
    var idx = e.currentTarget.dataset.idx;
    var openid = ctx.data.statList[idx].openid;
    wx.navigateTo({
      url: `/pages/sales/custom_detail/index?openid=${openid}&eId=${ctx.data.eId}`,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    app.routerIntercept()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let ctx = this;
    if ("time" == ctx.data.feedsType){
      ctx.setData({
        curPage:1,
        list:[],
        isLoading:false,
        isBottom:false
      });
      ctx.queryBehaviorTrail(function () {
        wx.stopPullDownRefresh();
      });
    } else if ("stat" == ctx.data.feedsType){
      ctx.setData({
        statList: [],
        statIsLoading: false,
        statCurPage: 1,
        statIsBottom: false,
      });
      ctx.queryStatList(function () {
        wx.stopPullDownRefresh();
      });
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let ctx = this;
    if (ctx.data.isLoading || ctx.data.statIsLoading) {
      return;
    }
    if ("time" == ctx.data.feedsType){
      ctx.setData({ curPage: ctx.data.curPage + 1 });
      ctx.queryBehaviorTrail();
    } else if ("stat" == ctx.data.feedsType){
      ctx.setData({ statCurPage: ctx.data.statCurPage + 1 });
      ctx.queryStatList();
    }
  },
}))